package books.search;

import java.util.Locale;

import org.apache.commons.collections.Predicate;

import books.BookInfo;

/**
 */
public class SearchByExamplePredicate implements Predicate {

    private BookInfo example;

    public SearchByExamplePredicate(final BookInfo anExample) {
        this.example = anExample;
    }

    /**
     *
     */
    @Override
    public boolean evaluate(final Object info) {
        BookInfo repoInfo = (BookInfo) info;
        BookInfo toSearch = this.getExample();

        return this.match(repoInfo.getTitle(), toSearch.getTitle())
                && this.match(repoInfo.getIsbn(), toSearch.getIsbn());
    }

    public BookInfo getExample() {
        return this.example;
    }

    public void setExample(final BookInfo example) {
        this.example = example;
    }

    private boolean match(final String string1, final String string2) {
        boolean match = false;
        String st1 = string1.toLowerCase(Locale.US);
        String st2 = string2.toLowerCase(Locale.US);

        if (st1.equalsIgnoreCase(st2)) {
            match = true;
        }
        if (st1.contains(st2) || st2.contains(st1)) {
            match = true;
        }
        return match;
    }

}
